package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.BaseManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.aspectj.weaver.ast.Var;
import org.assertj.core.error.ShouldAccept;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class BaseManageServiceImpl implements BaseManageService {

    @Autowired
    BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    SpuInfoMapper spuInfoMapper;
    @Autowired
    SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    SpuImageMapper spuImageMapper;


    //查询商品一级分类
    @Override
    public List<BaseCategory1> getCategory1() {
        List<BaseCategory1> category1List = baseCategory1Mapper.selectList(null);

        return category1List;
    }

    //查询商品二级分类
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        QueryWrapper<BaseCategory2> baseCategory2QueryWrapper = new QueryWrapper<>();
        baseCategory2QueryWrapper.eq("category1_id",category1Id);
        List<BaseCategory2> category2List = baseCategory2Mapper.selectList(baseCategory2QueryWrapper);
        return category2List;
    }

    //查询商品三级分类
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        QueryWrapper<BaseCategory3> baseCategory2QueryWrapper = new QueryWrapper<>();
        baseCategory2QueryWrapper.eq("category2_id",category2Id);
        List<BaseCategory3> category3List = baseCategory3Mapper.selectList(baseCategory2QueryWrapper);
        return category3List;
    }

    //查询商品平台属性
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        List<BaseAttrInfo> baseAttrInfoList = baseAttrInfoMapper.attrInfoList(category1Id,category2Id,category3Id);
        return baseAttrInfoList;
    }
    //保存商品平台属性
    @Override
    public void saveAttrInfo(BaseAttrInfo attrForm) {
        baseAttrInfoMapper.insert(attrForm);
        List<BaseAttrValue> attrValueList = attrForm.getAttrValueList();
        if(!CollectionUtils.isEmpty(attrValueList)){
            attrValueList.forEach(attrValue ->{
                attrValue.setAttrId(attrForm.getId());
                baseAttrValueMapper.insert(attrValue);
            });
        }
    }
    //根据平台id获取平台属性
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        QueryWrapper<BaseAttrValue> baseAttrValueQueryWrapper = new QueryWrapper<>();
        baseAttrValueQueryWrapper.eq("attr_id",attrId);
        List<BaseAttrValue> baseAttrValues = baseAttrValueMapper.selectList(baseAttrValueQueryWrapper);
        return baseAttrValues;
    }
    //更新平台属性
    @Override
    public void updateAttrInfo(BaseAttrInfo attrForm) {
        List<BaseAttrValue> attrValueList = attrForm.getAttrValueList();
        if(!CollectionUtils.isEmpty(attrValueList)){
            attrValueList.forEach(attrValue ->{
                if (attrValue.getId()==null){
                    attrValue.setAttrId(attrForm.getId());
                    baseAttrValueMapper.insert(attrValue);
                }else{
                baseAttrValueMapper.updateById(attrValue);
                }
            });
        }
    }

    //查询品牌列表
    @Override
    public IPage<BaseTrademark> baseTrademark(Long page,Long limit) {
        Page<BaseTrademark> baseTrademarkPage = new Page<>(page, limit);
        IPage<BaseTrademark> baseTrademarkIPage = baseTrademarkMapper.selectPage(baseTrademarkPage, null);
        return baseTrademarkIPage;
    }

    //查询分页spu属性
    @Override
    public IPage<SpuInfo> SpuFile(Long page, Long limit, Long category3Id) {
        Page<SpuInfo> spuInfoPage = new Page<>(page, limit);
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id", category3Id);
        IPage<SpuInfo> spuInfoIPage = spuInfoMapper.selectPage(spuInfoPage, spuInfoQueryWrapper);
        return spuInfoIPage;
    }

    //查询销售属性
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        List<BaseSaleAttr> saleAttrList = baseSaleAttrMapper.selectList(null);
        return saleAttrList;
    }
    //查询品牌属性
    @Override
    public List<BaseTrademark> getTrademarkList() {
        List<BaseTrademark> baseTrademarkList = baseTrademarkMapper.selectList(null);
        return baseTrademarkList;
    }

    //保存spu属性
    @Override
    public void saveSpuInfo(SpuInfo spuForm) {
        spuInfoMapper.insert(spuForm);
        //获取图片属性
        List<SpuImage> spuImageList = spuForm.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)){
            spuImageList.forEach(spuImage -> {
                spuImage.setSpuId(spuForm.getId());
                spuImageMapper.insert(spuImage);
            });
        }
        //获取销售属性
        List<SpuSaleAttr> spuSaleAttrList = spuForm.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)){
            spuSaleAttrList.forEach(spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuForm.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                //获取销售属性对象集合
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)){
                    spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValue.setSpuId(spuForm.getId());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            });
        }
        return;
    }

    //查询销售ID下的详细属性
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        List<SpuSaleAttr> saleAttrList = spuSaleAttrMapper.spuSaleAttrList(spuId);
        return saleAttrList;
    }
    //查询销售Id图片
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        QueryWrapper<SpuImage> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("spu_id",spuId);
        List<SpuImage> spuImageList = spuImageMapper.selectList(objectQueryWrapper);
        return spuImageList;
    }



    @Autowired
    SkuInfoMapper skuInfoMapper;
    @Autowired
    SkuImageMapper skuImageMapper;
    @Autowired
    SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    SkuSaleAttrValueMapper skuSaleAttrValueMapper;


    //添加sku详细信息
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {

        skuInfoMapper.insert(skuInfo);
        Long id = skuInfo.getId();
        //添加图片数据
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)){
            skuImageList.forEach(skuImage -> {
                skuImage.setSkuId(id);
                skuImageMapper.insert(skuImage);
            });
        }
        //添加sku详细属性
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)){
            skuAttrValueList.forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(id);
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }
        //添加sku销售属性
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValue.setSkuId(id);
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });

        return;
    }

    //查询分页sku对象

    @Override
    public IPage<SkuInfo> list(Long page, Long limit) {
        Page<SkuInfo> skuInfoPage = new Page<>(page, limit);
        IPage<SkuInfo> skuInfoIPage = skuInfoMapper.selectPage(skuInfoPage, null);
        return skuInfoIPage;

    }
    //上架
    @Override
    public void onSale(Long id) {
        SkuInfo skuInfo = skuInfoMapper.selectById(id);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);

    }
    //下架
    @Override
    public void cancelSale(Long id) {
        SkuInfo skuInfo = skuInfoMapper.selectById(id);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
    }

    @Autowired
    RedissonClient redissonClient;
  /*  @Autowired
    RedisTemplate redisTemplate;*/

   /* //获取库存信息,及图片信息
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        String s = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        String s1 = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
        //获取并判断redis中数据
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(s);
        if (null == skuInfo){
            RLock lock = redissonClient.getLock(s1);
            lock.lock(3,TimeUnit.SECONDS);
            skuInfo = skuInfoMapper.selectById(skuId);
            if (skuInfo != null) {
                QueryWrapper<SkuImage> skuImageQueryWrapper = new QueryWrapper<>();
                skuImageQueryWrapper.eq("sku_id", skuId);
                List<SkuImage> skuImages = skuImageMapper.selectList(skuImageQueryWrapper);
                skuInfo.setSkuImageList(skuImages);
                int i = new Random().nextInt(10);
                redisTemplate.opsForValue().set(s, skuInfo, i, TimeUnit.SECONDS);
            } else {
                //防止击穿
                skuInfo = new SkuInfo();
                redisTemplate.opsForValue().set(s, skuInfo, 10, TimeUnit.SECONDS);
            }
            lock.unlock();
        }else {
            try {

                Thread.sleep(1000);
                this.getSkuInfo(skuId);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        return skuInfo;
    }*/


    //redis
    @Autowired
    RedisTemplate redisTemplate;
    //获取库存信息,及图片信息
    //使用reids防止缓存穿透，雪崩，击穿
    /*@Override
    @GmallCache
    public SkuInfo getSkuInfo(Long skuId) {
        String s = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        String s1 = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
        //获取并判断redis中数据
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(s);
        if (null == skuInfo){

            Boolean b = redisTemplate.opsForValue().setIfAbsent(s1, "防止击穿",2,TimeUnit.SECONDS);
            if (b) {
                skuInfo = skuInfoMapper.selectById(skuId);
                if (skuInfo != null) {
                    QueryWrapper<SkuImage> skuImageQueryWrapper = new QueryWrapper<>();
                    skuImageQueryWrapper.eq("sku_id", skuId);
                    List<SkuImage> skuImages = skuImageMapper.selectList(skuImageQueryWrapper);
                    skuInfo.setSkuImageList(skuImages);
                    int i = new Random().nextInt(10);
                    redisTemplate.opsForValue().set(s, skuInfo, 200, TimeUnit.SECONDS);

                } else {
                    //防止击穿
                    skuInfo = new SkuInfo();
                    redisTemplate.opsForValue().set(s, skuInfo, 10, TimeUnit.SECONDS);
                }

                redisTemplate.delete(s1);
            }else {
                try {

                    Thread.sleep(500);
                    this.getSkuInfo(skuId);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        return skuInfo;

    }*/

    @Override
    @GmallCache(prefix = "sku:")
    public SkuInfo getSkuInfo(Long skuId) {
       SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null) {
            QueryWrapper<SkuImage> skuImageQueryWrapper = new QueryWrapper<>();
            skuImageQueryWrapper.eq("sku_id", skuId);
            List<SkuImage> skuImages = skuImageMapper.selectList(skuImageQueryWrapper);
            skuInfo.setSkuImageList(skuImages);
        }
        System.out.println("1111111111111111111111111111111111111111");
        return skuInfo;
    }

    @Autowired
    BaseCategoryViewMapper baseCategoryViewMapper;

    //查询物品等级列表
    @Override
    @GmallCache(prefix = "cate:")
    public BaseCategoryView getCategoryView(Long category3Id) {
        BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectById(category3Id);
        return baseCategoryView;
    }

    //查询商品售价

    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        BigDecimal price = skuInfo.getPrice();
        return price;

    }

    //查询库存销售参数
    @Override
    @GmallCache(prefix = "spu:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId) {
        List<SpuSaleAttr> saleAttrList = spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(skuId);
        System.out.println("saleAttrList = " + saleAttrList);
        return saleAttrList;
    }

    //根据销售属性获取spu页面
    @Override
    @GmallCache(prefix = "skuValue:")
    public Map<String, String> getSkuValueIdsMap(Long spuId) {
        List<Map<String,String>> mapList =  spuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        Map<String, String> stringMap = new HashMap<>();
        mapList.forEach(map ->{

            stringMap.put(map.get("value_ids"),String.valueOf(map.get("sku_id")));
        });
        System.out.println(mapList);
        System.out.println(stringMap);
        return stringMap;
    }
    //首页物品分类
    @Override
    public List<BaseCategoryView> getIndex() {
        List<BaseCategoryView> baseCategoryViews = baseCategoryViewMapper.selectList(null);
        return baseCategoryViews;
    }
}
